#include "../main.h"

#define FILE_MAXSIZE 1024
#define page 1024

int createDir(char *dirpath)
{
	if (!access(dirpath, 0))
	{
		return -1;
	}
	else
	{
		int status = mkdir(dirpath, 0777);
		return status;
	}
}

int createfile(char *filepath)
{
	if (isExist(filepath))
	{
		return 1;
	}
	OUT_DEBUG(DEBUG, "filepath:%s", filepath);
	FILE *pfile = fopen(filepath, "wb");
	fclose(pfile);
	return 1;
}

int appendFile(char *filepath, char *bytes)
{
	if (!isExist(filepath))
	{
		return 0;
	}
	FILE *fp = fopen(filepath, "a+");
	//int totalsize = getfilesize2(filepath);
	//fseek(fp, currentindex, SEEK_CUR);
	fputs(bytes, fp);
	fclose(fp);
	return 1;
}

int isExist(char *path)
{
	int ret = 0;
	if (access(path, R_OK) != -1)
	{
		ret = 1;
	}
	return ret;
}

FileInfo *readFile(char *filepath, long offset, int size)
{
	long totalsize = get_file_totalSize(filepath);
	if (offset >= totalsize)
	{
		return NULL;
	}
	if (size > totalsize - offset)
	{
		size = totalsize - offset;
	}
	if (size > 0)
	{
		FileInfo *fileInfo = NULL;
		fileInfo = create_file_info();
		FILE *fp = fopen(filepath, "rb");
		char buff[size];
		memset(buff, 0, size);
		fseek(fp, offset, SEEK_SET);
		int read_size = fread(buff, 1, size, fp);
		if (read_size != size)
		{
			OUT_DEBUG(DEBUG, "file read maybe error size:%d", read_size);
		}
		fileInfo->bytes = (char *)malloc(size);
		if (fileInfo->bytes == NULL)
		{
			OUT_DEBUG(DEBUG, "FILE BYTES MALLOC ERROR,size:%d", size);
		}
		memset(fileInfo->bytes, 0, size);
		memcpy(fileInfo->bytes, buff, size);

		int i = 0;
		for (i = 0; i < 10; i++)
		{
			unsigned char x = *(fileInfo->bytes + i);
			printf("%02x  ", x);
		}
		printf("\n");

		fileInfo->filePath = stringCopy(filepath, strlen(filepath));
		char *filename = getfilename(filepath);
		fileInfo->fileName = stringCopy(filename, strlen(filename));
		fileInfo->totalsize = totalsize;
		fileInfo->currentIndex = offset;
		fileInfo->size = size;
		fclose(fp);
		free(filename);
		filename = NULL;

		for (i = 0; i < 10; i++)
		{
			unsigned char x = *(fileInfo->bytes + i);
			printf("%02x  ", x);
		}
		printf("\n");

		return fileInfo;
	}
	else
	{
		return NULL;
	}
}

int writeFileInfo(FileInfo *fileinfo, char *filepath)
{
	if (!isExist(filepath))
	{
		return 0;
	}
	else
	{
		FILE *fp = fopen(filepath, "rb+");
		if (fp != NULL)
		{
			fseek(fp, fileinfo->currentIndex, SEEK_SET);
			fwrite(fileinfo->bytes, fileinfo->size, 1, fp);
			fclose(fp);
		}
		return 1;
	}
}

void readFileByFileInfoRecord(FileInfoRecord *fileInfoRecord)
{
	if (fileInfoRecord->isend)
	{
		return;
	}
	else
	{
		FILE *fp = fopen(fileInfoRecord->filePath, "r");
		long currentIndex = fileInfoRecord->currentIndex;
		long totalsize = getfilesize(fileInfoRecord->filePath);
		fileInfoRecord->totalSize = getfilesize(fileInfoRecord->filePath);
		if (totalsize - currentIndex >= page * FILE_MAXSIZE)
		{
			fseek(fp, currentIndex, SEEK_CUR);
			char buff[page * FILE_MAXSIZE];
			int read_size = fread(buff, 1, page * FILE_MAXSIZE, fp);
			fclose(fp);
			int i;
			for (i = 0; i < page; i++)
			{
				FileInfo *info = (FileInfo *)malloc(sizeof(FileInfo *));
				info->filePath = fileInfoRecord->filePath;
				info->totalsize = totalsize;
				info->currentIndex = currentIndex + i * FILE_MAXSIZE;
				char zbuff[FILE_MAXSIZE];
				copyByte(zbuff, buff, i * FILE_MAXSIZE, 0, FILE_MAXSIZE);
				info->bytes = zbuff;
				info->size = FILE_MAXSIZE;
				info->fileName = getfilename(fileInfoRecord->filePath);
				fileInfoRecord->currentIndex += FILE_MAXSIZE;
			}
		}
		else
		{
			long size = totalsize - currentIndex;
			fseek(fp, currentIndex, SEEK_CUR);
			char buff[size];
			memset(buff, 0, size);
			int read_size = fread(buff, 1, size, fp);
			printf("read file size:%d\n", read_size);
			fclose(fp);
			int i = 0;
			while (1)
			{
				if (size - i * FILE_MAXSIZE <= FILE_MAXSIZE)
				{
					int leftsize = size - i * FILE_MAXSIZE;
					FileInfo *info = (FileInfo *)malloc(sizeof(FileInfo *));
					info->filePath = fileInfoRecord->filePath;
					info->totalsize = totalsize;
					info->currentIndex = currentIndex + i * FILE_MAXSIZE;
					char zbuff[FILE_MAXSIZE];
					copyByte(zbuff, buff, i * FILE_MAXSIZE, 0, leftsize);
					info->bytes = zbuff;
					info->size = leftsize;
					info->fileName = getfilename(fileInfoRecord->filePath);
					fileInfoRecord->currentIndex += leftsize;
					fileInfoRecord->isend = 1;
					i++;
					break;
				}
				else
				{
					FileInfo *info = (FileInfo *)malloc(sizeof(FileInfo *));
					info->filePath = fileInfoRecord->filePath;
					info->totalsize = totalsize;
					info->currentIndex = currentIndex + i * FILE_MAXSIZE;
					char zbuff[FILE_MAXSIZE];
					copyByte(zbuff, buff, i * FILE_MAXSIZE, 0, FILE_MAXSIZE);
					info->bytes = zbuff;
					info->size = FILE_MAXSIZE;
					info->fileName = getfilename(fileInfoRecord->filePath);
					fileInfoRecord->currentIndex += FILE_MAXSIZE;
					i++;
				}
			}
		}
	}
}

unsigned long getfilesize(char *filepath)
{
	unsigned long filesize = -1;
	FILE *pf;
	pf = fopen(filepath, "r");
	if (pf == NULL)
	{
		return filesize;
	}
	fseek(pf, 0L, SEEK_END);
	filesize = ftell(pf);
	fclose(pf);
	return filesize;
}

long get_file_totalSize(char *filepath)
{
	struct stat statbuf;
	stat(filepath, &statbuf);
	long size = statbuf.st_size;
	return size;
}

void copyByte(char *target, char *src, int srcpos, int tarpos, int length)
{
	memcpy(target + tarpos, src + srcpos, length);
}

char *getfilename(char *path)
{
	int i, j = 0;
	for (i = 0; path[i]; i++)
	{
		if (path[i] == '\\')
		{
			j = i;
		}
		if (path[i] == '/')
		{
			j = i;
		}
	}
	int size = strlen(path) - j;
	char *name = (char *)malloc(size);
	memset(name, 0, size);
	memcpy(name, path + j + 1, size);
	return name;
}

int check_has_disk(long total_size)
{
	char value[128];
	memset(value, 0, sizeof(value));
	shell_cmd("df -k | grep '/dev/mmcblk' | awk '{print $4}'", value);
	if (strlen(value))
	{
		long disk_left_total = atol(value);
		long share_size = 0;
		memset(value, 0, sizeof(value));
		int ret = get_value("appctrl.@appctrl[0].share", &value);
		if (ret == 1 && strlen(value))
		{
			share_size = atol(value);
		}
		total_size = total_size / 1024;
		if (disk_left_total - share_size > total_size)
		{
			return 1;
		}
	}
	return 0;
}

//上传图片并压缩
void post_img_file(char *file_path, char *file_name)
{
	char result[200];
	char url[1000];
	memset(result, 0, sizeof(result));
	memset(url, 0, sizeof(url));
	snprintf(url, sizeof(url), "curl -F \"file=@%s; filename=%s\" %s", file_path, file_name, post_image_url);
	OUT_DEBUG(DEBUG, "req:%s", url);
	shell_cmd(url, result);
	if (result != NULL)
	{
		cJSON *pRank = NULL, *pValue = NULL;
		pRank = cJSON_Parse(result);
		if (pRank == NULL)
		{
			OUT_DEBUG(DEBUG, "json 解析异常");
			OUT_DEBUG(DEBUG, "result:%s", result);
		}
		else
		{
			char *file_name = NULL;
			pValue = cJSON_GetObjectItem(pRank, "url");
			if (pValue != NULL && pValue->type == cJSON_String)
			{
				int length = strlen(pValue->valuestring);
				char *img_url = charCopy(pValue->valuestring, length + 1);
				img_url[length] = '\0';
				char *photo_list_txt = charJoin(file_dir, "photos.txt");
				createfile(photo_list_txt);
				char item[300];
				sprintf(item, "%s=%s;", file_path, img_url);
				appendFile(photo_list_txt, item);
				free(photo_list_txt);
				photo_list_txt = NULL;
			}
			cJSON_Delete(pRank);
		}
	}
	OUT_DEBUG(DEBUG, "POST_RESULT:%s", result);
}

char *create_dist_file(int file_type, char *file_name)
{
	char *dist_file_dir = NULL;
	int ret = -2;
	if (file_type == 0)
	{
		dist_file_dir = charJoin(file_dir, movie_dir);
		ret = createDir(dist_file_dir);
	}
	else if (file_type == 1)
	{
		dist_file_dir = charJoin(file_dir, photo_dir);
		ret = createDir(dist_file_dir);
	}
	else if (file_type == 2)
	{
		dist_file_dir = charJoin(file_dir, music_dir);
		ret = createDir(dist_file_dir);
	}
	//OUT_DEBUG(DEBUG, "file_dir:%s,create result:%d,file_type:%d", dist_file_dir, ret, file_type);
	if (dist_file_dir != NULL)
	{
		char *file_path = charJoin(dist_file_dir, "/");
		file_path = charJoin(file_path, file_name);
		if (dist_file_dir != NULL)
		{
			free(dist_file_dir);
			dist_file_dir = NULL;
		}
		return file_path;
	}
	else
	{
		return NULL;
	}
}

FileInfo *create_file_info()
{
	FileInfo *fileInfo = (FileInfo *)malloc(sizeof(FileInfo));
	fileInfo->filePath = NULL;
	fileInfo->fileName = NULL;
	fileInfo->bytes = NULL;
	fileInfo->md5_value = NULL;
	fileInfo->size = 0;
	fileInfo->totalsize = 0;
	fileInfo->currentIndex = 0;
	return fileInfo;
}

void freeFileInfo(FileInfo *fileInfo)
{
	if (fileInfo != NULL)
	{
		if (fileInfo->filePath != NULL)
		{
			free(fileInfo->filePath);
			fileInfo->filePath = NULL;
		}
		if (fileInfo->fileName != NULL)
		{
			free(fileInfo->fileName);
			fileInfo->fileName = NULL;
		}
		//OUT_DEBUG(DEBUG, "a301");
		//OUT_DEBUG(DEBUG, "a304");
		// if (fileInfo->bytes != NULL)
		// {
		// 	OUT_DEBUG(DEBUG, "a3041");
		// 	free(fileInfo->bytes);
		// 	OUT_DEBUG(DEBUG, "a3042");
		// 	fileInfo->bytes = NULL;
		// 	OUT_DEBUG(DEBUG, "a3043");
		// }
		// OUT_DEBUG(DEBUG, "a303");
		if (fileInfo->md5_value != NULL)
		{
			free(fileInfo->md5_value);
			fileInfo->md5_value = NULL;
		}
		free(fileInfo);
		fileInfo = NULL;
	}
}
